package cn.btks.resultintegration.achievements.service.impl;

import cn.btks.commonserver.result.Constants;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.commonserver.util.FileUtil;
import cn.btks.commonserver.util.ZipMultiFile;
import cn.btks.resultintegration.achievements.pojo.AchievementsFileTemp;
import cn.btks.resultintegration.achievements.pojo.AchievementsTemp;
import cn.btks.resultintegration.achievements.pojo.AchievementsType;
import cn.btks.resultintegration.achievements.pojo.VectorFileCategory;
import cn.btks.resultintegration.achievements.repository.AchievementsFileTempRepository;
import cn.btks.resultintegration.achievements.repository.AchievementsTypeRepository;
import cn.btks.resultintegration.achievements.service.AchievementsFileTempService;
import cn.btks.resultintegration.achievements.service.AchievementsTempService;
import cn.btks.resultintegration.achievements.service.AchievementsTypeService;
import cn.btks.resultintegration.achievements.service.VectorFileCategoryService;
import cn.btks.resultintegration.feign.FeignClient.BackManageClient;
import cn.btks.resultintegration.feign.FeignObject.City;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author lijun
 * @Date 2021/2/20 9:11
 */
@Service
@Transactional
public class AchievementsFileTempServiceImpl implements AchievementsFileTempService {

    @Autowired
    AchievementsFileTempRepository achievementsFileTempRepository;

    @Autowired
    AchievementsFileTempService achievementsFileTempService;

    @Autowired
    AchievementsTypeService achievementsTypeService;

    @Autowired
    BackManageClient backManageClient;

    @Autowired
    VectorFileCategoryService vectorFileCategoryService;

    @Autowired
    AchievementsTypeRepository achievementsTypeRepository;

    @Autowired
    AchievementsTempService achievementsTempService;

    @Override
    public List<AchievementsFileTemp> findAllByFileName(String fileName) {
        return achievementsFileTempRepository.findAllByFileName(fileName);
    }

    @Override
    public ResultState zipFileByCityId(Long cityId, HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<>();
        String cityName = "";
        ResultState resultState = backManageClient.findById(cityId);
        if(resultState.getData() != null){
            Object data = resultState.getData();
            City city1 = JSONArray.parseObject(JSON.toJSONString(data), City.class);
            if(city1 != null){
                cityName = city1.getName();
            }
        }
        List<AchievementsType> achievementsTypeList = achievementsTypeService.findAll();
        AchievementsType vectorType = achievementsTypeList.stream().filter(s->s.getCode().equals("VECTOR")).findFirst().get();
        AchievementsType textType = achievementsTypeList.stream().filter(s->s.getCode().equals("TEXT")).findFirst().get();
        AchievementsType evidenceType = achievementsTypeList.stream().filter(s->s.getCode().equals("EVIDENCE")).findFirst().get();
        List<Map<String,Object>> achievementVectorFilePaths = achievementsFileTempRepository.findAllByAchievementsTypeIdAndCityId1(vectorType.getId(), cityId);
        List<Map<String,Object>> achievementTextFilePaths = achievementsFileTempRepository.findAllByAchievementsTypeIdAndCityId1(textType.getId(), cityId);
        List<Map<String,Object>> achievementEvidenceFilePaths = achievementsFileTempRepository.findAllByAchievementsTypeIdAndCityId1(evidenceType.getId(), cityId);
        String realPath = request.getSession(true).getServletContext().getRealPath("//");
        String vectorZipFilePath = "";
        String textZipFilePath = "";
        String evidenceZipFilePath = "";
        if(achievementVectorFilePaths != null && achievementVectorFilePaths.size() > 0){
            List<String> filePathList = new ArrayList<>();
            for(Map<String,Object> item : achievementVectorFilePaths){
                String filePath = realPath + item.get("filePath");
                filePathList.add(filePath);
            }
            vectorZipFilePath = ZipMultiFile.zipMultiFile(filePathList,cityName+"_VECTOR",request);
        }
        if(achievementTextFilePaths != null && achievementTextFilePaths.size() > 0){
            List<String> filePathList = new ArrayList<>();
            for(Map<String,Object> item : achievementTextFilePaths){
                String filePath = realPath + item.get("filePath");
                filePathList.add(filePath);
            }
            textZipFilePath = ZipMultiFile.zipMultiFile(filePathList,cityName+"_TEXT",request);
        }
        if(achievementEvidenceFilePaths != null && achievementEvidenceFilePaths.size() > 0){
            List<String> filePathList = new ArrayList<>();
            for(Map<String,Object> item : achievementEvidenceFilePaths){
                String filePath = realPath + item.get("filePath");
                filePathList.add(filePath);
            }
            evidenceZipFilePath = ZipMultiFile.zipMultiFile(filePathList,cityName+"_EVIDENCE",request);
        }
        if(!StringUtils.isEmpty(vectorZipFilePath) || !StringUtils.isEmpty(textZipFilePath) || !StringUtils.isEmpty(evidenceZipFilePath)){
            resultMap.put("VECTOR",vectorZipFilePath);
            resultMap.put("TEXT",textZipFilePath);
            resultMap.put("EVIDENCE",evidenceZipFilePath);
            return new ResultState(StateInfo.ZIP_OK.getCode(), StateInfo.ZIP_OK.getMsg(), resultMap);
        }else {
            return new ResultState(StateInfo.ZIP_ERROR.getCode(), StateInfo.ZIP_ERROR.getMsg(), resultMap);
        }
    }

    @Override
    public ResultState zipFileCategory(Long fileCategory, HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<>();
        List<VectorFileCategory> vectorFileCategoryList = vectorFileCategoryService.findAll();
        VectorFileCategory vectorFileCategory = vectorFileCategoryList.stream().filter(s -> s.getId().equals(fileCategory)).findFirst().get();
        List<AchievementsType> achievementsTypeList = achievementsTypeService.findAll();
        AchievementsType vectorType = achievementsTypeList.stream().filter(s->s.getCode().equals("VECTOR")).findFirst().get();
        AchievementsType textType = achievementsTypeList.stream().filter(s->s.getCode().equals("TEXT")).findFirst().get();
        AchievementsType evidenceType = achievementsTypeList.stream().filter(s->s.getCode().equals("EVIDENCE")).findFirst().get();
        List<Map<String,Object>> achievementVectorFilePaths = achievementsFileTempRepository.findAllByAchievementsTypeIdAndFileCategory1(vectorType.getId(), vectorFileCategory.getId());
        List<Map<String,Object>> achievementTextFilePaths = achievementsFileTempRepository.findAllByAchievementsTypeIdAndFileCategory1(textType.getId(), vectorFileCategory.getId());
        List<Map<String,Object>> achievementEvidenceFilePaths = achievementsFileTempRepository.findAllByAchievementsTypeIdAndFileCategory1(evidenceType.getId(), vectorFileCategory.getId());
        String realPath = request.getSession(true).getServletContext().getRealPath("//");
        String vectorZipFilePath = "";
        String textZipFilePath = "";
        String evidenceZipFilePath = "";
        if(achievementVectorFilePaths != null && achievementVectorFilePaths.size() > 0){
            List<String> filePathList = new ArrayList<>();
            for(Map<String,Object> item : achievementVectorFilePaths){
                String filePath = realPath + item.get("filePath");
                filePathList.add(filePath);
            }
            vectorZipFilePath = ZipMultiFile.zipMultiFile(filePathList,vectorFileCategory.getName()+"_VECTOR",request);
        }
        if(achievementTextFilePaths != null && achievementTextFilePaths.size() > 0){
            List<String> filePathList = new ArrayList<>();
            for(Map<String,Object> item : achievementTextFilePaths){
                String filePath = realPath + item.get("filePath");
                filePathList.add(filePath);
            }
            textZipFilePath = ZipMultiFile.zipMultiFile(filePathList,vectorFileCategory.getName()+"_TEXT",request);
        }
        if(achievementEvidenceFilePaths != null && achievementEvidenceFilePaths.size() > 0){
            List<String> filePathList = new ArrayList<>();
            for(Map<String,Object> item : achievementEvidenceFilePaths){
                String filePath = realPath + item.get("filePath");
                filePathList.add(filePath);
            }
            evidenceZipFilePath = ZipMultiFile.zipMultiFile(filePathList,vectorFileCategory.getName()+"_EVIDENCE",request);
        }
        if(!StringUtils.isEmpty(vectorZipFilePath) || !StringUtils.isEmpty(textZipFilePath) || !StringUtils.isEmpty(evidenceZipFilePath)){
            resultMap.put("VECTOR",vectorZipFilePath);
            resultMap.put("TEXT",textZipFilePath);
            resultMap.put("EVIDENCE",evidenceZipFilePath);
            return new ResultState(StateInfo.ZIP_OK.getCode(), StateInfo.ZIP_OK.getMsg(), resultMap);
        }else {
            return new ResultState(StateInfo.ZIP_ERROR.getCode(), StateInfo.ZIP_ERROR.getMsg(), resultMap);
        }
    }

    @Override
    public ResultState zipAllFile() {
        return null;
    }

    @Override
    public ResultState updateEvidenceFiles(Long achievementTempId, List<MultipartFile> multipartFiles, HttpServletRequest request) {
        if (multipartFiles != null) {
            List<AchievementsFileTemp> achievementsFileList = new ArrayList<>();
            AchievementsTemp achievementsTemp = achievementsTempService.findById(achievementTempId);
            List<AchievementsType> achievementsTypes = achievementsTypeRepository.findAll();
            AchievementsType achievementsEvidenceType = achievementsTypes.stream().filter(s -> s.getCode().equals("EVIDENCE")).findFirst().get();
            String fileEvidencePath = Constants.ACHIEVEMENTS_EVIDENCE_FILE;
            List<AchievementsFileTemp> achievementsFileTemps = new ArrayList<>();
            for (int i = 0; i < multipartFiles.size(); i++) {
                String uuid = UUID.randomUUID().toString();
                AchievementsFileTemp achievementsFile = new AchievementsFileTemp();
                String fjName = uuid + "_" + multipartFiles.get(i).getOriginalFilename();
                String fileOriginalFileName = multipartFiles.get(i).getOriginalFilename();
                String pathname = request.getSession(true).getServletContext().getRealPath("//") + fileEvidencePath + fjName;
                String filePathFinal = fileEvidencePath + fjName;
                System.out.println(request.getSession(true).getServletContext().getRealPath("//"));
                if (FileUtil.fileUpload(multipartFiles.get(i), pathname)) {
                    return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
                }
                String suffix = filePathFinal.substring(filePathFinal.lastIndexOf(".") + 1);
                if (!StringUtils.isEmpty(suffix)) {
                    achievementsFile.setFileType(suffix);
                }
                achievementsFile.setFilePath(filePathFinal);
                achievementsFile.setFileName(fileOriginalFileName);
                achievementsFile.setAchievementsTypeId(achievementsEvidenceType.getId());
                achievementsFile.setIsHistory(0);
                achievementsFileList.add(achievementsFile);
                achievementsFileTemps.add(achievementsFile);
                achievementsFile.setContent(achievementsTemp.getContent());
            }
            if (achievementsFileTemps.size() <= 0) {
                return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg(), "文件上传失败");
            }
            for (AchievementsFileTemp file : achievementsFileTemps) {
                file.setAchievements(achievementsTemp);
            }
            achievementsFileTempRepository.deleteEvidenceByAchievementsTempId(achievementsTemp.getId(),achievementsEvidenceType.getId());
            List<AchievementsFileTemp> achievementsFileTemps1 = achievementsFileTempRepository.saveAll(achievementsFileTemps);
            return achievementsFileTemps != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), achievementsFileTemps):
                    new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
        }
        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState saveAllEvidenceFiles(List<AchievementsFileTemp> achievementsFileTempList) {
        List<AchievementsFileTemp> achievementsFileTemps = achievementsFileTempRepository.saveAll(achievementsFileTempList);
        return achievementsFileTemps != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), achievementsFileTemps):
                new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }
}
